﻿using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HRM.Model;
using GalaSoft.MvvmLight.Ioc;
using System.Windows;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System.ComponentModel;
using System.Windows.Data;
using HRM.Helper;

namespace HRM.ViewModel
{
    public class FunctionViewModel : ViewModelBase
    {
        private IFunction _functionService;
        private NguoiSuDung _user;

        public List<ChucNang> Functions
        {
            get
            {
                if (SimpleIoc.Default.IsRegistered<List<ChucNang>>())
                {
                    return SimpleIoc.Default.GetInstance<List<ChucNang>>();
                }

                else
                {
#if !DEBUG
                    MessageBox.Show("Object is dispose");
#endif
                    return new List<ChucNang>();
                }
            }
        }

        private ChucNang _selectedItem;

        public ChucNang SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                if (_selectedItem != value)
                {
                    _selectedItem = value;
                    RaisePropertyChanged("SelectedItem");
                }
            }
        }

        public RelayCommand SaveCommand
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (SelectedItem != null)
                    {
                        if (_functionService.Update(SelectedItem)) Refresh();
                        Messenger.Default.Send(new StatusMessage("Thay đổi thành công.", 3000, StatusType.Done));
                    }
                }, () => _user.GetPermisstion);
            }
        }

        public void Refresh()
        {
            if (SimpleIoc.Default.IsRegistered<List<ChucNang>>())
            {
                var list = SimpleIoc.Default.GetInstance<List<ChucNang>>();
                list = _functionService.GetFunctions(SimpleIoc.Default.GetInstance<NguoiSuDung>());
                MainViewModel main = SimpleIoc.Default.GetInstance<MainViewModel>();
                ICollectionView _view = CollectionViewSource.GetDefaultView(list);
                _view.GroupDescriptions.Clear();
                _view.GroupDescriptions.Add(new PropertyGroupDescription("Nhom"));
                main.FunctionsView = _view;
            }
        }

        public FunctionViewModel(IFunction service)
        {
            _functionService = service;
            _user = SimpleIoc.Default.GetInstance<NguoiSuDung>();
        }
    }
}
